<template name="component-name">
  <div class="app-container gencode-container">
    <el-row :gutter="20">
      <el-col :offset="6" :span="12">
        <el-card shadow="always">
          <el-steps :active="stepActive" simple>
            <el-step title="数据库连接" icon="el-icon-edit" />
            <el-step title="应用配置" icon="el-icon-document" />
          </el-steps>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top:4px;">
      <el-col :offset="6" :span="12">
        <el-card v-loading="connectDataSourceLoading" element-loading-text="服务器连接中..." element-loading-spinner="el-icon-loading" :body-style="{ 'height': 'calc(100vh - 150px)',padding: '24px', position: 'relative', overflow: 'hidden', 'overflow-y': 'auto'}">
          <template v-if="stepActive === 1">
            <el-divider content-position="left">基础配置</el-divider>
            <el-row>
              <el-col :span="24">
                <el-form ref="baseConfigForm" :rules="baseConfigRules" :model="baseConfig" label-position="left" label-width="90px" style="width: 80%; margin-left:50px;">
                  <el-form-item label="作者:" prop="author" label-width="100px">
                    <el-input v-model="baseConfig.author" clearable placeholder="请输入作者" />
                  </el-form-item>
                  <el-form-item label="基础包名称:" prop="basePackage" label-width="100px">
                    <el-input v-model="baseConfig.basePackage" clearable placeholder="例:com.fintech.pangu" />
                  </el-form-item>
                  <el-form-item label="项目名称:" prop="artifact" label-width="100px">
                    <el-input v-model="baseConfig.artifact" clearable placeholder="例:user-api-web" />
                  </el-form-item>
                  <el-form-item label="描述:" prop="description" label-width="100px">
                    <el-input v-model="baseConfig.description" clearable placeholder="请输入描述" />
                  </el-form-item>
                  <el-form-item label="父依赖版本:" prop="parentVersion" label-width="100px">
                    <el-select v-model="baseConfig.parentVersion" clearable placeholder="请选择父依赖版本">
                      <el-option v-for="item in parentVersionList" :key="item" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-divider content-position="left">数据源配置</el-divider>
            <el-row>
              <el-col :span="24">
                <el-form ref="dataSourceForm" :rules="dataSourceRules" :model="dataSource" label-position="left" label-width="90px" style="width: 80%; margin-left:50px;">
                  <el-form-item label="用户名:" prop="userName" label-width="100px">
                    <el-input v-model="dataSource.userName" clearable placeholder="请输入用户名" />
                  </el-form-item>
                  <el-form-item label="密码:" prop="password" label-width="100px">
                    <el-input v-model="dataSource.password" clearable placeholder="请输入密码" />
                  </el-form-item>
                  <el-form-item label="数据库地址:" prop="url" label-width="100px">
                    <el-input v-model="dataSource.url" clearable placeholder="请输入数据库URL" />
                  </el-form-item>
                  <el-form-item>
                    <el-button class="card-footer" type="primary" @click="connectDataSource">连接</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </template>

          <template v-if="stepActive === 2">
            <el-row>
              <el-col :span="24">
                <el-divider content-position="left">已选列表</el-divider>
                <div class="box-list">
                  <div class="box-empty" :class="{'box-hide': hideBoxText}">请设置表字段内容</div>
                  <el-tag v-for="tag in tagTableList" :key="tag.name" closable style="margin: 0 10px 5px 0;" @close="closeTableTag(tag)">{{ tag.name }}</el-tag>
                </div>
              </el-col>
            </el-row>
            <el-divider />
            <el-row>
              <el-col :span="24">
                <el-table
                  ref="multipleDataTable"
                  v-loading="listLoading"
                  :data="tableList"
                  :row-key="getRowKeys"
                  border
                  fit
                  highlight-current-row
                  header-cell-class-name="table-header-cell"
                  style="width: 100%; margin-top:10px;"
                  empty-text="请创建数据表信息"
                >
                  <el-table-column
                    prop="sId"
                    label="序号"
                    type="index"
                    width="50px"
                  />
                  <el-table-column
                    prop="tableName"
                    label="表名"
                  />
                  <el-table-column
                    prop="tableComment"
                    label="描述"
                    :show-overflow-tooltip="true"
                  />
                  <el-table-column
                    prop="engine"
                    label="数据库引擎"
                    width="100px"
                  />
                  <el-table-column
                    prop="tableCollation"
                    label="字符集"
                  />
                  <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                    <template slot-scope="{row}">
                      <el-button type="success" size="small" @click="handleFieldConfig(row)">字段配置</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination v-show="total>0" :total="total" :page.sync="dataSource.current" :limit.sync="dataSource.size" @pagination="getTableList" />
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24" style="margin-top:20px">
                <el-button type="primary" style="float:right" @click="generateCode">生成代码</el-button>
              </el-col>
            </el-row>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="字段配置" :visible.sync="dialogTableFiledFormVisible" :close-on-click-modal="false" :close-on-press-escape="true" width="50%" @close="closeTableFiledDialog">
      <el-table
        ref="fieldTable"
        :data="fieldList"
        :row-key="getRowKeys"
        border
        fit
        highlight-current-row
        header-cell-class-name="table-header-cell"
        style="width: 100%; margin-top:10px;"
        empty-text="请创建数据表信息"
      >
        <el-table-column
          prop="sId"
          label="序号"
          type="index"
          width="100px"
        />
        <el-table-column
          prop="columnName"
          label="字段名"
        />
        <el-table-column
          prop="columnComment"
          label="描述"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="dataType"
          label="字段类型"
        />
        <el-table-column label="请求参数" align="center">
          <template slot-scope="scope">
            <el-select v-model="fieldList[scope.$index].columnQuery" clearable placeholder="非查询条件">
              <el-option label="精确查询" value="1" />
              <el-option label="范围查询" value="2" />
              <el-option label="模糊查询" value="3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="返回参数" width="80px" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="fieldList[scope.$index].columnTableShow"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="新增/修改" width="80px" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="fieldList[scope.$index].columnCreateAndUpdate"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
            />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableFiledFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createConfig">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { fetchTables, generatorCode, getParentVersion } from '@/api/generator.js'

export default {
  name: 'SysGenerator',
  components: { Pagination },
  data() {
    return {
      stepActive: 1,
      baseConfig: {
        author: '',
        basePackage: '',
        artifact: '',
        description: '',
        parentVersion: ''
      },
      dataSource: {
        current: 1,
        size: 10,
        userName: '',
        password: '',
        url: ''
      },
      baseConfigRules: {
        author: [{ required: true, message: '作者不能为空', trigger: 'change' }],
        basePackage: [{ required: true, message: '基础包名不能为空', trigger: 'change' }],
        artifact: [{ required: true, message: '项目名称不能为空', trigger: 'change' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'change' }],
        parentVersion: [{ required: true, message: '父依赖版本不能为空', trigger: 'change' }]
      },
      dataSourceRules: {
        userName: [{ required: true, message: '用户名不能为空', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'change' }],
        url: [{ required: true, message: '数据库地址不能为空', trigger: 'change' }]
      },
      total: 0,
      listLoading: false,
      tableList: [],
      parentVersionList: [],
      tagTableList: [],
      dialogTableFiledFormVisible: false,
      fieldList: [],
      tableName: '',
      connectDataSourceLoading: false,
      hideBoxText: false,
      generateCodeList: {
        dataSource: '',
        baseConfig: '',
        tableList: []
      }
    }
  },
  created() {
    this.getParentVersion()
  },
  methods: {
    getRowKeys(row) {
      return row.name
    },
    nextStep() {
      if (this.stepActive++ > 2) {
        this.stepActive = 1
      }
    },
    backStep() {
      if (this.stepActive-- < 0) {
        this.stepActive = 1
      }
    },
    getParentVersion() {
      getParentVersion().then(response => {
        const res = response.retBody
        this.parentVersionList = res
      })
    },
    getTableList() {
      this.listLoading = true
      return fetchTables(this.dataSource).then(response => {
        const res = response.retBody
        this.tableList = res.records
        this.total = res.total
      }).finally(() => {
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    connectDataSource() {
      Promise.all(
        ['baseConfigForm', 'dataSourceForm'].map(form => {
          return this.$refs[form].validate()
        })
      ).then(() => {
        this.connectDataSourceLoading = true
        this.getTableList().then(() => {
          this.nextStep()
        }).finally(() => {
          this.connectDataSourceLoading = false
        })
      }).catch((e) => {})
    },
    // handleRowClick(row, column, event) {
    //   this.$refs.multipleDataTable.toggleRowSelection(row)
    // },
    handleFieldConfig(row) {
      const table = this.tableList.filter(item => {
        if (item.tableName === row.tableName) {
          return item
        }
      })
      this.fieldList = table[0].filedList
      this.tableName = row.tableName
      this.dialogTableFiledFormVisible = true
    },
    closeTableFiledDialog() {

    },
    closeTableTag(tag) {
      this.tagTableList.splice(this.tagTableList.indexOf(tag), 1)

      this.generateCodeList.tableList = this.generateCodeList.tableList.filter(item => {
        return item.tableName !== tag.name
      })
      if (this.tagTableList && this.tagTableList.length === 0) {
        this.hideBoxText = false
      }
    },
    createConfig() {
      const fields = []
      this.fieldList.forEach(item => {
        const fieldInfo = {}
        fieldInfo.fieldName = item.columnName
        fieldInfo.fetch = item.columnQuery || '0'
        fieldInfo.createUpdate = item.columnCreateAndUpdate
        fieldInfo.vo = item.columnTableShow
        fields.push(fieldInfo)
      })
      const tableInfo = {}
      tableInfo.tableName = this.tableName
      tableInfo.fields = fields

      this.generateCodeList.dataSource = { ...this.dataSource }
      this.generateCodeList.baseConfig = { ...this.baseConfig }
      if (this.generateCodeList.tableList && this.generateCodeList.tableList.length > 0) {
        this.generateCodeList.tableList = this.generateCodeList.tableList.filter(item => {
          return item.tableName !== this.tableName
        })
      }
      this.generateCodeList.tableList.push(tableInfo)

      const tagInfo = {}
      tagInfo.name = this.tableName
      tagInfo.type = ''
      let isTagExists = false
      if (this.tagTableList && this.tagTableList.length > 0) {
        isTagExists = this.tagTableList.some(item => {
          if (item.name === this.tableName) {
            return true
          }
        })
      }
      if (!isTagExists) {
        this.tagTableList.push(tagInfo)
      }
      this.hideBoxText = true
      this.dialogTableFiledFormVisible = false
    },

    generateCode() {
      if (!this.generateCodeList.tableList || this.generateCodeList.tableList.length === 0) {
        this.$notify({
          title: '提示',
          message: '未设置相关表信息',
          type: 'warning',
          duration: 1500
        })
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '代码生成中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      generatorCode(this.generateCodeList).then(response => {
        const blob = response
        const fileName = this.baseConfig.artifact + '.zip'
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName)
        } else {
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // 释放内存
          window.URL.revokeObjectURL(link.href)
        }
      }).finally(() => {
        setTimeout(() => {
          loading.close()
        }, 500)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.gencode-container{
    width: 100%;
    height: 100%;
    background-image: url('../../assets/gencode_images/gencode_bng.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
.card-footer{
  float: right;
}
.btn-right{
  float: right;
  margin-left: 20px;
}
.box-list{
  min-height: 85px;
  border-radius: 4px;
  border: 1px dashed #e1e1e1;
  /* margin-bottom: 20px; */
  padding: 24px;
  .box-empty{
    position: absolute;
    text-align: center;
    height: 20px;
    font-size: 20px;
    top: 50%;
    width: 100%;
    margin-top: -10px;
    color: #ccc;
    line-height: 70px;
  }
}
.box-hide{
  display:none;
}
</style>
